class Api::V1::PayController < Api::V1::BaseController
  def create
    params[:pay_method] ||= 'wepay'

    if params[:order_id].presence
      order = Order.find params[:order_id]
      if order.blank?
        render json: { result: false, message: '订单不存在.' }, status: :ok and return
      end
      if not order.pending?
        render json: { result: false, message: '订单不能支付.' }, status: :ok and return
      end
      trade_no = order.trade_no
      total_fee = order.total_fee
      order.update_column("pay_method", params[:pay_method])
    elsif params[:orders].presence
      trade_no = "MP" + Time.now.strftime('%Y%m%d%H%M%S') + rand(999).to_s  
      total_fee = 0
      params[:orders].split(',').each do |order_id|
        order = Order.find order_id
        if order.blank?
          next
        end
        if not order.pending?
          next
        end
        order.update_attributes(mix_trade_no: trade_no, pay_method: params[:pay_method])
        total_fee = total_fee + order.total_fee
      end
    end

    if total_fee == 0
      render json: { result: false, message: '支付价格为0元，不能支付.' }, status: :ok and return
    end
    
    if params[:pay_method] == 'wepay'
      prepay_params = {
        body: "#{Setting.fetch("app_name")}订单支付",
        out_trade_no: trade_no,
        total_fee: (total_fee * 100).to_i,
        spbill_create_ip: request.remote_ip,
        notify_url: Figaro.env.wechat_pay_notify_url,
        trade_type: 'APP'
      }
      prepay_result = WxPay::Service.invoke_unifiedorder prepay_params
      if prepay_result.success?
        pay_params = {
          prepayid: prepay_result['prepay_id'],
          noncestr: prepay_result['nonce_str']
        }
        pay_result = WxPay::Service.generate_app_pay_req pay_params
        render json: { result: true, message: '获取微信支付数据成功.', data: pay_result }, status: :ok
      else
        render json: { result: false, message: '申请微信订单失败.', data: prepay_result }, status: :ok
      end
    elsif params[:pay_method] == 'alipay'
      @client = Alipay::Client.new(
        url: Figaro.env.alipay_url,
        app_id: Figaro.env.alipay_app_id,
        app_private_key: Figaro.env.alipay_app_private_key,
        alipay_public_key: Figaro.env.alipay_public_key
      )
      pay_result = @client.sdk_execute(
        method: 'alipay.trade.app.pay',
        notify_url: Figaro.env.alipay_pay_notify_url,
        biz_content: {
          out_trade_no: "#{trade_no}",
          product_code: 'QUICK_MSECURITY_PAY',
          total_amount: "#{total_fee}",
          subject: "#{Setting.fetch("app_name")}订单支付"
        }.to_json(ascii_only: true),
        timestamp: Time.now.strftime('%Y-%m-%d %H:%M:%S')
      )
      render json: { result: true, message: '获取支付宝支付数据成功.', data: pay_result }, status: :ok
    elsif params[:pay_method] == 'moneybag'
      if @current_user.moneybag == 0 || total_fee > @current_user.moneybag
        render json: { result: false, message: '余额不足,请充值后再支付.', data: pay_result }, status: :ok and return
      end
      begin
        @current_user.moneybag = @current_user.moneybag - total_fee
        @current_user.save!
        send_phone = ''
        send_shop = ''
        if params[:orders].presence
          orders = Order.where(mix_trade_no: trade_no)
          orders.each do |order|
            order.update_attributes(state: :checkouted)
            order.order_items.update_all(state: :checkouted)
            order.shop.update(balance: order.shop.balance + order.total_fee)
            order.send_notify("支付成功.", 'Native', 'order_details', '{ "id": ' + order.id.to_s + ' }')
            order.compute_bonus
            send_phone = order.shop.phone
          end
        elsif params[:order_id].presence
          order = Order.find_by_trade_no trade_no
          order.update_attributes(state: :checkouted)
          order.order_items.update_all(state: :checkouted)
          order.shop.update(balance: order.shop.balance + order.total_fee)
          order.send_notify("支付成功.", 'Native', 'order_details', '{ "id": ' + @order.id.to_s + ' }')
          order.compute_bonus
          send_phone = order.shop.phone
        end
        @reponse = Qcloud::Sms.single_sender(send_phone, "271384", ["#{trade_no}"])
        render json: { result: true, message: '支付成功.' }, status: :ok
      rescue => exception
        render json: { result: false, message: '支付失败.' }, status: :ok
      end
    elsif params[:pay_method] == 'cash'
      begin
        send_phone = ''
        send_shop = ''
        if params[:orders].presence
          orders = Order.where(mix_trade_no: trade_no)
          orders.each do |order|
            order.update_attributes(state: :sent)
            order.order_items.update_all(state: :sent)
            order.shop.update(balance: order.shop.balance + order.total_fee)
            order.send_notify("支付成功.", 'Native', 'order_details', '{ "id": ' + order.id.to_s + ' }')
            order.compute_bonus
            send_phone = order.shop.phone
          end
        elsif params[:order_id].presence
          order = Order.find_by_trade_no trade_no
          order.update_attributes(state: :sent)
          order.order_items.update_all(state: :sent)
          order.shop.update(balance: order.shop.balance + order.total_fee)
          order.send_notify("下单成功.", 'Native', 'order_details', '{ "id": ' + @order.id.to_s + ' }')
          order.compute_bonus
          send_phone = order.shop.phone
        end
        @reponse = Qcloud::Sms.single_sender(send_phone, "271384", ["#{trade_no}"])
        render json: { result: true, message: '支付成功.' }, status: :ok
      rescue => exception
        render json: { result: false, message: '支付失败.' }, status: :ok
      end
    end
  end
end
